package com.activeMQ;

import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.DeliveryMode;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.MessageProducer;
import javax.jms.Session;
import javax.jms.TextMessage;

import org.apache.activemq.ActiveMQConnectionFactory;
/**
 * 生产者
 * @author gxkj-042
 *
 */
public class Sender {
	public static void main(String[] args) throws JMSException {
		
		//建立ConnectionFactory工厂对象，需要填入用户名、密码、连接地址，默认地址：tcp://localhost:61616
		ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(
				"zhangsan", 
				"password",
				"tcp://localhost:61616");
		
		//通过connectionFactory工厂对象创建connection连接，并用connection的start方法开启连接，
		//connection默认是关闭的
		Connection connection = connectionFactory.createConnection();
		connection.start();
		
		//通过connection创建session会话（上下文环境对象），用于接收消息，配置参数2为签收模式
		//Session session = connection.createSession(Boolean.FALSE, Session.AUTO_ACKNOWLEDGE);
		//开启事物,使用手动签收的方式
		Session session = connection.createSession(Boolean.TRUE, Session.CLIENT_ACKNOWLEDGE);
		
		//通过session创建destination对象，这是一个客户端用来生产数据的对象
		Destination destination = session.createQueue("queue1");
		
		//通过session对象创建消息的发送对象（生产者和消费者)MessageProducer/MessageConsumer
		//MessageProducer messageProducer = session.createProducer(destination);
		MessageProducer messageProducer = session.createProducer(null);
		
		//使用messageProducer的setDeliveryMode方法为其设置持久化特性
		//messageProducer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
		
		for (int i = 0; i < 100; i++) {
			TextMessage textMessage = session.createTextMessage();
			textMessage.setText("这是消息内容，ID为："+i);
			//messageProducer.send(textMessage);
			messageProducer.send(destination, textMessage, DeliveryMode.NON_PERSISTENT, i, 1000 * 60);
		}
		//事物开启后，必须要提交事物才能发送数据
		session.commit();
		
		//关闭连接
		if(connection != null){
			connection.close();
		}
		System.out.println("数据发送完成...");
	}
}
